<?php
class DocumentsController extends AppController {
	var $name = 'Documents';
	var $helpers = array('Html', 'Form');	
	
	function index () {
		$this->loadModel('Privilege');
		$privileges = $this->Privilege->find('list');
		$this->set(compact('privileges'));
		$this->loadModel('Region');
		$regions = $this->Region->find('list');
		$this->set(compact('regions'));
		$this->loadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set(compact('facultets'));
	}
	function privileges_students(){
		 $privilege_id = $this->data['Document']['privilege_id'] ;
		 
		 $this->set('privilege_id', $privilege_id);
		 
		 $this->loadModel('PrivilegesStudentinfo');

		 $this->loadModel('Privilege');
		 $privileges = $this->Privilege->find('list');
		 $this->set(compact('privileges'));
		 // курсы 
		$this->loadModel('Course');
		$courses = $this->Course->find('list');	
		$this->set(compact('facultets', 'professions', 'courses'));
		// форма и тип обучения
		$this->loadModel('Learningform');
		$learningforms = $this->Learningform->find('list');
		$this->loadModel('Learningtype');
		$this->set('learningforms', $learningforms);
		$learningtypes = $this->Learningtype->find('list');
		$this->set('learningtypes', $learningtypes);
		//
		$this->loadModel('Studentinfo');
		$this->loadModel('Studentgroup');	
		// специальность
		$this->loadModel('Profession');
						 
		 $tmp_students = $this->PrivilegesStudentinfo->find('all', array('conditions' => array('PrivilegesStudentinfo.privilege_id' =>  $privilege_id)));
		 $student_learning_info = array();
		 foreach ($tmp_students as $tmp_student):
		 $array_line = array();
		 $student_id = $tmp_student['Studentinfo']['student_id'];
		 
		// находим его группу
		$student = $this->Studentinfo->Student->find('all', array('conditions' => array('Student.id' => $student_id)));
		// debug($student);
		$studentgroup_id = $student[0]['Studentgroup']['id'];
		
		$studentgroup = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.id' => $studentgroup_id), 'recursive' => 0,));
		$this->set(compact('studentgroup'));			

		$profession = $this->Profession->find('all', array('conditions' => array('Profession.id' => $studentgroup[0]['Course']['profession_id']), 'recursive' => 0));
		// debug($profession);
		// факультет 
		$arr_element = array('facultet' => $profession[0]['Facultet']['name']);
		array_push($array_line, $arr_element);
		// специальность
		$arr_element = array('profession' => $profession[0]['Profession']['name']);
		array_push($array_line, $arr_element);
		// курс 
		$arr_element = array('course' => $courses[$studentgroup[0]['Studentgroup']['course_id']]);
		array_push($array_line, $arr_element);
		// группа
		$arr_element = array('group' => $studentgroup[0]['Studentgroup']['name']);
		array_push($array_line, $arr_element);	
		// форма обуч	
		$arr_element = array('lform' => $student[0]['Student']['learningform_id']);
		array_push($array_line, $arr_element);	
		// тип обуч
		$arr_element = array('ltype' => $student[0]['Student']['learningtype_id']);
		array_push($array_line, $arr_element);					
		array_push($student_learning_info, $array_line);
		 endforeach;
		 $this->set('student_learning_info', $student_learning_info);
		 $this->set('tmp_students', $tmp_students);
		 
		
		 
		$this->render('/','blank','privileges_students');
	}
	
	function comm_students () {
		$this->loadModel('Student');

		$sessionsettings = ''; 
		$selectedfacultet = '';
		$selectedprofession = '';
		$selectedcourse = '';
		$selectedgroup = ''; 
		if ($this->Session->check('Settings')){
			$sessionsettings = $this->Session->read('Settings');
			$selectedfacultet = $sessionsettings['Settings']['selectedfacultet'];
			$selectedprofession = $sessionsettings['Settings']['selectedprofession'];
			$selectedcourse = $sessionsettings['Settings']['selectedcourse'];
			$selectedgroup = $sessionsettings['Settings']['selectedgroup'];			
		}
		$this->set(compact('selectedfacultet', $selectedfacultet)); 
		$this->set(compact('selectedprofession', $selectedprofession)); 
		$this->set(compact('selectedcourse', $selectedcourse));
		$this->set(compact('selectedgroup', $selectedgroup));
		$this->loadModel('Profession');
		$selectedprofessions = $this->Profession->find('list');
		$this->set(compact('selectedprofessions'));			
		/********************************************************************************************/		
		// выбран факультет спецальность курс группа
		/********************************************************************************************/		
		if ($selectedfacultet && $selectedprofession && $selectedcourse && $selectedgroup) {
			// $students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroup), 'recursive' => 0));
			//формируем массив id групп
			$selectedgroups_ids = array();
			array_push($selectedgroups_ids, $selectedgroup);
		}
		/********************************************************************************************/		
		// выбран факультет специлальность курс
		/********************************************************************************************/		
		else if ($selectedfacultet && $selectedprofession && $selectedcourse && !$selectedgroup) {
			// выбираем группы курса
			$this->loadModel('Studentgroup');
			$selectedgroups = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.course_id' => $selectedcourse), 
			'recursive' => 0,
			'order' => 'Studentgroup.id ASC',
			'fields' => array('Studentgroup.id')));
			//формируем массив id групп
			$selectedgroups_ids = array();
			foreach ($selectedgroups as $element):
			array_push($selectedgroups_ids, $element['Studentgroup']['id']);
			endforeach;
			// выбираем студентов
		//	$students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroups_ids), 'recursive' => 0));
		}
		/********************************************************************************************/		
		// выбран факультет специальность
		/********************************************************************************************/		
		else if ($selectedfacultet && $selectedprofession && !$selectedcourse && !$selectedgroup) {
			// выбираем курсы специальности
			$this->loadModel('Course');
			$selectedcourses = $this->Course->find('all', array('conditions' => array('Course.profession_id' => $selectedprofession),
			'recursive' => 0,
			'order' => 'Course.id ASC',
			'fields' => array('Course.id')));
			$selectedcourses_ids = array();
			foreach ($selectedcourses as $element):
			array_push($selectedcourses_ids, $element['Course']['id']);
			endforeach;
			// выбираем группы курсов
			$this->loadModel('Studentgroup');
			$selectedgroups = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.course_id' => $selectedcourses_ids), 
			'recursive' => 0,
			'order' => 'Studentgroup.id ASC',
			'fields' => array('Studentgroup.id')));
			//формируем массив id групп
			$selectedgroups_ids = array();
			foreach ($selectedgroups as $element):
			array_push($selectedgroups_ids, $element['Studentgroup']['id']);
			endforeach;
			// выбираем студентов
		//	$students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroups_ids), 'recursive' => 0));
		}
		/********************************************************************************************/		
		// выбран факультет
		/********************************************************************************************/		
		if ($selectedfacultet && !$selectedprofession && !$selectedcourse && !$selectedgroup) {
			// выбираем специальности факультета
			$this->loadModel('Profession');
			$selectedprofessions = $this->Profession->find('all', array('conditions' => array('Profession.facultet_id'), 'recursive' => 0));
			$selectedprofessions_ids = array();
			foreach ($selectedprofessions as $element):
			array_push($selectedprofessions_ids, $element['Profession']['id']);
			endforeach;			
			// выбираем курсы специальностей
			$this->loadModel('Course');
			$selectedcourses = $this->Course->find('all', array('conditions' => array('Course.profession_id' => $selectedprofessions_ids),
			'recursive' => 0,
	//		'order' => 'Course.id ASC',
			'fields' => array('Course.id')));
			$selectedcourses_ids = array();
			foreach ($selectedcourses as $element):
			array_push($selectedcourses_ids, $element['Course']['id']);
			endforeach;
			// выбираем группы курсов
			$this->loadModel('Studentgroup');
			$selectedgroups = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.course_id' => $selectedcourses_ids), 
			'recursive' => 0,
	//		'order' => 'Studentgroup.id ASC',
			'fields' => array('Studentgroup.id')));
			//формируем массив id групп
			$selectedgroups_ids = array();
			foreach ($selectedgroups as $element):
			array_push($selectedgroups_ids, $element['Studentgroup']['id']);
			endforeach;
			// выбираем студентов
			// $students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroups_ids), 'recursive' => 0));
			}
		/********************************************************************************************/
		// выбрано все факультеты
		/********************************************************************************************/		
		else if (!$selectedfacultet && !$selectedprofession && !$selectedcourse && !$selectedgroup) {
			//$this->Student->recursive = 0;
			//$students = $this->Student->find('all');
			// выбираем группы курсов
			$this->loadModel('Studentgroup');
			$selectedgroups = $this->Studentgroup->find('all');
			//формируем массив id групп
			$selectedgroups_ids = array();
			foreach ($selectedgroups as $element):
			array_push($selectedgroups_ids, $element['Studentgroup']['id']);
			endforeach;			
		}
		// устнавливем пагинацию
		$this->Student->recursive = 0;
		$conditions =  array('Student.studentgroup_id' => $selectedgroups_ids, 'Student.learningtype_id' => 2);
		$this->paginate['conditions'] = $conditions;
		$students = $this->paginate('Student');
		$this->set('students', $students);
		
		// выбираем инфо для заполнения столбцов в таблице
		$this->loadModel('Learningform');
		$learningforms = $this->Learningform->find('list');
		$this->loadModel('Learningtype');
		$this->set('learningforms', $learningforms);
		$learningtypes = $this->Learningtype->find('list');
		$this->set('learningtypes', $learningtypes);
		// id массива professions начинается с 0 так что  чобы получить profession с id = 8 нужно взять 7 элемент массива
		$this->LoadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set('facultets', $facultets);
		$this->LoadModel('Course');
		$courses = $this->Course->find('all', array('recursive' => 0));
		// id массива courses начинается с 0 так что чтобы получить course с id = 12 нужно взять 11 элемент массива 
		$this->set('courses', $courses);		
		
	}
	/*
	 * вывод стцудентов СНГ Кавказу и средней АЗИИ
	 */
	function students_nonrus () {
		$this->loadModel('Student');
		$this->loadModel('Studentinfo');
		$searched_students_ids = array();
		$regions_to_search = array(5,6,7,9,15,20,26);
		/*
		 * ищем студентов со статусом учится по нужным регионам
		 */
		$students = $this->Studentinfo->find('all', array('conditions' => array('Studentinfo.region_id' => $regions_to_search), 'recursive' => 0));
		foreach ($students as $student):
		$student_id = $student['Studentinfo']['student_id'];
		$tmp_student = $this->Student->find('all', array('conditions' => array('Student.id' => $student_id), 'recursive' => 0));
		if ($tmp_student[0]['Student']['studentstate_id'] == 1) {
			array_push($searched_students_ids,  $student['Studentinfo']['id']);
		}
		endforeach;
		$students = $this->Studentinfo->find('all', array('conditions' => array('Studentinfo.id' => $searched_students_ids)));
		$this->set('students', $students);
		
		// id массива professions начинается с 0 так что  чобы получить profession с id = 8 нужно взять 7 элемент массива
		$this->LoadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set('facultets', $facultets);
		$this->LoadModel('Course');
		$courses = $this->Course->find('all', array('recursive' => 0));
		// id массива courses начинается с 0 так что чтобы получить course с id = 12 нужно взять 11 элемент массива 
		$this->set('courses', $courses);
		// выбираем группы
		$studentgroups = $this->Student->Studentgroup->find('all', array ('recursive' => 0));
		$this->set(compact('studentgroups'));
		// выбираем области
		$this->loadModel('Region');
		$regions = $this->Region->find('list');
		$this->set('regions', $regions);
	}
	/*
	 * вывод студентов 1 курса по области
	 */
	function students_from_region_new () {
		$region_id = $this->data['Document']['region_id'] ;
		$this->loadModel('Studentinfo');
		$students = $this->Studentinfo->find('all', array('conditions' => array('Studentinfo.region_id' => $region_id, 'Studentinfo.enrollment_date' => '2010-09-01'), 'recursive' => 0));
		$this->set('students', $students);
		// id массива professions начинается с 0 так что  чобы получить profession с id = 8 нужно взять 7 элемент массива
		$this->LoadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set('facultets', $facultets);
		$this->LoadModel('Course');
		$courses = $this->Course->find('all', array('recursive' => 0));
		// id массива courses начинается с 0 так что чтобы получить course с id = 12 нужно взять 11 элемент массива 
		$this->set('courses', $courses);
		// выбираем группы
				$this->loadModel('Student');
		$studentgroups = $this->Student->Studentgroup->find('all', array ('recursive' => 0));
		$this->set(compact('studentgroups'));		
	}
	function students_from_region_old () {
		$region_id = $this->data['Document']['region_id'] ;
		$this->loadModel('Studentinfo');
		$students_ids = array();
		$students = $this->Studentinfo->find('all', array('conditions' => array('Studentinfo.region_id' => $region_id), 'recursive' => 0));
		foreach ($students as $student):
			array_push($students_ids, $student['Studentinfo']['student_id']);
		endforeach;
		

		// id массива professions начинается с 0 так что  чобы получить profession с id = 8 нужно взять 7 элемент массива
		$this->LoadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set('facultets', $facultets);
		$this->LoadModel('Course');
		$courses = $this->Course->find('all', array('recursive' => 0));
		// id массива courses начинается с 0 так что чтобы получить course с id = 12 нужно взять 11 элемент массива 
		$this->set('courses', $courses);
		// выбираем группы
		$this->loadModel('Student');
		$studentgroups = $this->Student->Studentgroup->find('all', array ('recursive' => 0));
		$this->set(compact('studentgroups'));		

		// получаем id последних курсов
		$last_courses_ids = array();
		$professions = $this->Facultet->Profession->find('all');
		foreach ($professions as $profession):
		$courses_count = count($profession['Course']);
		$last_course_id = $profession['Course'][$courses_count-2]['id'];
		array_push($last_courses_ids, $last_course_id);
		endforeach;
		// получем id груп последних курсов
		$last_courses_groups_ids = array();
		$last_courses_groups = $this->Student->Studentgroup->find('all', array('conditions' => array('Studentgroup.course_id' => $last_courses_ids, 'Studentgroup.number NOT LIKE ' => 'AA.%', 'Studentgroup.number NOT LIKE ' => 'XX.%')));
		foreach ($last_courses_groups as $last_courses_group):
		array_push($last_courses_groups_ids, $last_courses_group['Studentgroup']['id']);
		endforeach;
		
		$tmpstudents = $this->Student->find('all', array('conditions' => array('Student.id' => $students_ids, 'Student.studentgroup_id' => $last_courses_groups_ids)));
		$ids = array();
		foreach ($tmpstudents as $tmpstudent):
		array_push($ids, $tmpstudent['Student']['id']);
		endforeach;
		$students = $this->Studentinfo->find('all', array('conditions' => array('Studentinfo.student_id' => $ids), 'recursive' => 0));
		$this->set('students', $students);
	}
	/*
	 * провека информации из пенсионного фонда и генерация файла
	 * 
	 */
	function check_pension_fond_info() {
		// получили файл
		$csvfile = fopen($this->data["Document"]["csvfile"]["tmp_name"],"r");
		// подклчаем модели
		$this->loadModel('Studentinfo');
		$this->loadModel('Student');
		$this->loadModel('Facultet');
		
		
		$this->loadModel('Course');
		$courses = $this->Course->find('all');
		//debug($courses);

		$errors = array();		
		// запускаем цикл перебора записей
		while(!(feof($csvfile))) {
			// считали запись
			$line = fgetcsv($csvfile, 10000, ";");
			// 0 фамилия
			// 1 имя
			// 2 отчество
			// 3 дата рождения
			$lastname = iconv('Windows-1251', 'UTF-8',trim($line[0]));
			$firstname =  iconv('Windows-1251', 'UTF-8',trim($line[1]));
			$surname =  iconv('Windows-1251', 'UTF-8',trim($line[2]));
			$birthdate = iconv('Windows-1251', 'UTF-8',trim($line[3]));
			
			$studentinfo = $this->Studentinfo->find('all', array('conditions' => array('Studentinfo.lastname' => $lastname, 
																					'Studentinfo.firstname' => $firstname,
																					'Studentinfo.surname' => $surname,
																					'Studentinfo.birthdate' => $birthdate
																					), 'recursive' => -1, 
			'fields' => array('Studentinfo.lastname','Studentinfo.firstname','Studentinfo.surname','Studentinfo.birthdate','Studentinfo.student_id',)));
			//debug ($studentinfo);
			 if (count($studentinfo)== 0){
				array_push($line, iconv('UTF-8', 'Windows-1251', 'Студент с такими ФИО и датой рождения не найден'));
				
			} elseif (count($studentinfo)> 1){
				array_push($line, iconv('UTF-8', 'Windows-1251', 'Найдено более одного студента с такими ФИО и датой рождения'));
							
			} else {
				$laststring = '';
				$student_id = $studentinfo[0]['Studentinfo']['student_id'];
				$student = $this->Student->find('all', array('conditions' => array('Student.id' => $student_id), 'recursive' => 0));
				//debug($student);
				foreach ($courses as $course):
				if ($course['Course']['id'] == $student[0]['Studentgroup']['course_id']){
					$profession_name = $course['Profession']['name'];
					$course_name = $course['Course']['name'];
					break;
				}
				endforeach;
				$laststring = $student[0]['Studentstate']['name'].' '.$student[0]['Studentgroup']['name'].' '.$course_name.' '.$profession_name;
				//debug ($laststring);
				array_push($line, iconv('UTF-8', 'Windows-1251', $laststring));
			} 
			array_push($errors, $line);
			
			//debug($line);
		}
		$this->set('errors',$errors);
			
		$this->render('/', 'blank', 'check_pension_fond_info');
	}
	/*
	 * списки всех учащихся студентов у тоторых status_id = 1 
	 */
	function all_students(){
		$this->loadModel('Facultet');
		$this->loadModel('Profession');
		$this->loadModel('Course');
		$this->loadModel('Studentgroup');
		$this->loadModel('Student');
		$this->loadModel('Studentinfo');
		
		$facultet_id = $this->data['Document']['facultet_id'];
		$studentslist = array();
		$titlest = array(iconv('UTF-8', 'Windows-1251',"Профессия;Курс;Группа;id студента;Имя;Фамилия;Отчество;Состояние;id гражданства; id региона;пол; Дата поступления в вуз; Дата рождения;Серия паспорта;Номер паспорта;Данные паспортные;Адрес по прописке;Место рождения;Адрес фактический;Окончил школу;id типа документа об образовании;данные документа об образовании;Телефон;мобильный;Email;ИНН;Мед полис;Пенсионный св-во (СНИЛС);Прививки;ДОПинфо;Иностранный язык;Контракт;Ребенок1дата рождения;Ребенок1 инфо;Ребенок2дата рождения;Ребенок2 инфо;Целевое Направление id региона;Целевое Направление инфо;Тип Супруга;ФИО;Паспорт данные;Тип Родственника 1;ФИО;Работа;должность;Телефон;Мобильный;email;Адрес;Паспортные данные;Тип Родственника 2;ФИО;Работа;должность;Телефон;Мобильный;email;Адрес;Паспортные данные;Льгота;"));
		array_push($studentslist, $titlest);
		/* $facultets = $this->Facultet->find('all', array('recursive' => -1));
		foreach($facultets as $facultet): */
			$professions = $this->Profession->find('all', array('conditions' => array('Profession.facultet_id' => $facultet_id), 'recursive' => -1));
			foreach ($professions as $profession):
				$courses = $this->Course->find('all', array('conditions' => array('Course.profession_id' => $profession['Profession']['id']), 'recursive' => -1));
				foreach ($courses as $course):
					$groups = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.course_id' => $course['Course']['id']), 'recursive' => -1));
					foreach ($groups as $group):
						$students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $group['Studentgroup']['id'], 'Student.studentstate_id' => 1) , 'recursive' => -1 ));
						foreach ($students as $student):
							$tmp_student = $this->Studentinfo->find('first', array('conditions' => array('Studentinfo.student_id' => $student['Student']['id'])));
							//debug ($tmp_student);
							$student_arr = array();
						//	$student_arr['facultet'] = iconv('UTF-8', 'Windows-1251', $facultet['Facultet']['name']);
							$student_arr['profession'] = iconv('UTF-8', 'Windows-1251', $profession['Profession']['name']);
							$student_arr['course'] = iconv('UTF-8', 'Windows-1251', $course['Course']['name']);
							$student_arr['group'] = iconv('UTF-8', 'Windows-1251', $group['Studentgroup']['name']);
							$student_arr['id'] = $student['Student']['id'];
							$student_arr['lastname'] = iconv('UTF-8', 'Windows-1251', $student['Student']['lastname']);
							$student_arr['firstname'] = iconv('UTF-8', 'Windows-1251', $student['Student']['firstname']);
							$student_arr['surname'] = iconv('UTF-8', 'Windows-1251', $student['Student']['surname']);
							$student_arr['studentstate_id'] = $student['Student']['studentstate_id'];
							$student_arr['citizenship_id'] = $tmp_student['Studentinfo']['citizenship_id'];	
							$student_arr['region_id'] =  $tmp_student['Region']['id'];
							$student_arr['gender'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Gender']['name']));
							
							$student_arr['enrollment_date'] = $tmp_student['Studentinfo']['enrollment_date'];
							$student_arr['birthdate'] = $tmp_student['Studentinfo']['birthdate'];
							$student_arr['passport_ser'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Studentinfo']['passport_ser']));
							$student_arr['passport_num'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Studentinfo']['passport_num']));
							$student_arr['passport_data'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Studentinfo']['passport_data']));
							$student_arr['passport_adress'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Studentinfo']['passport_adress']));
							$student_arr['passport_birth_place'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Studentinfo']['passport_birth_place']));
							$student_arr['adress'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Studentinfo']['adress']));
							$student_arr['schoolgraduated'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Studentinfo']['schoolgraduated']));
							$student_arr['educationdoctype_id '] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Studentinfo']['educationdoctype_id']));
							$student_arr['educationdocdata'] = iconv('UTF-8', 'Windows-1251', str_replace(';', ' ', str_replace("\r\n",' ', $tmp_student['Studentinfo']['educationdocdata'])));
							$student_arr['phone'] = $tmp_student['Studentinfo']['phone'];
							$student_arr['mobile'] = $tmp_student['Studentinfo']['mobile'];
							$student_arr['email'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Studentinfo']['email']));
							$student_arr['inn'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Studentinfo']['inn']));
							$student_arr['insurance'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Studentinfo']['insurance']));
							$student_arr['pension_certificate'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Studentinfo']['pension_certificate']));
							$student_arr['inoculations'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Studentinfo']['inoculations']));
							$student_arr['moreinfo'] = iconv('UTF-8', 'Windows-1251', str_replace(';', ' ', str_replace("\r\n",' ',$tmp_student['Studentinfo']['moreinfo'])))  ;
							$student_arr['foreignlanguage'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Foreignlanguage']['name']));
							 
							if (isset($tmp_student['Contract'][0])) {
								//debug($tmp_student);
								//die();
								$student_arr['contract'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Contract'][0]['data']));
							}
							else {
								$student_arr['contract'] = '';
							}
							if (isset($tmp_student['Baby'][0])) {
								$student_arr['baby1_birthday'] = $tmp_student['Baby'][0]['birthdate'];
								$student_arr['baby1_info'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Baby'][0]['info']));
							} else {
								$student_arr['baby1_birthday'] = '';
								$student_arr['baby1_info'] = '';
							}
							if (isset($tmp_student['Baby'][1])) {
								$student_arr['baby2_birthday'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Baby'][1]['birthdate']));
								$student_arr['baby2_info'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Baby'][1]['info']));
							} else {
								$student_arr['baby2_birthday'] = '';
								$student_arr['baby2_info'] = '';
							}					

							if (isset($tmp_student['Targetingintake'][0])){
								$student_arr['tgintake_region_id'] = $tmp_student['Targetingintake'][0]['region_id'];
								$student_arr['tgintake_info'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Targetingintake'][0]['info']));
							} else {
								$student_arr['tgintake_region_id'] = '';
								$student_arr['tgintake_info'] = '';
							}
							
							if (isset($tmp_student['Mate'][0])){
								$student_arr['matestatus_id'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Mate'][0]['matestatus_id']));
								$student_arr['fio'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Mate'][0]['fio']));
								$student_arr['mate_passport_data'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Mate'][0]['passport_data']));
							} else {
								$student_arr['matestatus_id'] = '';
								$student_arr['fio'] = '';
								$student_arr['mate_passport_data'] = '';
							}
							if (isset($tmp_student['Relative[0]'])){
								$student_arr['relativestype_id'] = $tmp_student[0]['relative']['relativestype_id'];
								$student_arr['relativefio'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student[0]['relative']['fio']));
								$student_arr['relativejob'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student[0]['relative']['job']));
								$student_arr['relativejobstatus'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student[0]['relative']['jobstatus']));
								$student_arr['relativephone'] = $tmp_student[0]['relative']['phone'];
								$student_arr['relativemobile'] = $tmp_student[0]['relative']['mobile'];
								$student_arr['relativeemail'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student[0]['relative']['email']));
								$student_arr['relativeadress'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student[0]['relative']['adress']));
								$student_arr['relativepassport_data'] = $tmp_student[0]['relative']['passport_data'];
							} else {
								$student_arr['relativestype_id'] ='';
								$student_arr['relativefio'] ='';
								$student_arr['relativejob'] ='';
								$student_arr['relativejobstatus'] ='';
								$student_arr['relativephone'] ='';
								$student_arr['relativemobile'] ='';
								$student_arr['relativeemail'] ='';
								$student_arr['relativeadress'] ='';
								$student_arr['relativepassport_data'] ='';
							}
							if (isset($tmp_student['Relative[1]'])){
								$student_arr['relativestype_id1'] = $tmp_student[1]['relative']['relativestype_id'];
								$student_arr['relativefio1'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student[1]['relative']['fio']));
								$student_arr['relativejob1'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student[1]['relative']['job']));
								$student_arr['relativejobstatus1'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student[1]['relative']['jobstatus']));
								$student_arr['relativephone1'] = $tmp_student[1]['relative']['phone'];
								$student_arr['relativemobile1'] = $tmp_student[1]['relative']['mobile'];
								$student_arr['relativeemail1'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student[1]['relative']['email']));
								$student_arr['relativeadress1'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student[1]['relative']['adress']));
								$student_arr['relativepassport_data1'] = $tmp_student[1]['relative']['passport_data'];
							} else {
								$student_arr['relativestype_id1'] ='';
								$student_arr['relativefio1'] ='';
								$student_arr['relativejob1'] ='';
								$student_arr['relativejobstatus1'] ='';
								$student_arr['relativephone1'] ='';
								$student_arr['relativemobile1'] ='';
								$student_arr['relativeemail1'] ='';
								$student_arr['relativeadress1'] ='';
								$student_arr['relativepassport_data1'] ='';
							}
							if (isset($tmp_student['Privilege'][0])){
								$student_arr['privilege'] = iconv('UTF-8', 'Windows-1251', str_replace("\r\n",' ', $tmp_student['Privilege'][0]['name']));
							} else {
								$student_arr['privilege'] = '';
							} 
							array_push($studentslist, $student_arr);
						endforeach;
						// break 4;
						// debug($studentslist);
						//die();
					endforeach;
					//break 2; 
				endforeach;
			endforeach;
		/* endforeach; */
		$this->set('studentslist', $studentslist);
		$this->render('/', 'blank', 'all_students');
	}
	
	
	/*
	 * вывод всех отчисленных за прошлый год по настоящее время
	 */
	function lastyearexpelled() {
		
		Configure::write('debug', 0);
		
		$this->loadModel('Order');
		
		$ordertype_ids = array(18,19,20,21,22,23,24);
		$current_year = date(Y);
		$corrent_month = date(m);
		if ($corrent_month > 7){
			$search_date = $current_year-1;
			$search_date = $search_date.'-09-01';
		} else {
			$search_date = $current_year-2;
			$search_date = $search_date.'-09-01';
		}
		//debug($search_date);
		$orders = $this->Order->find('all', array('conditions' => array('Order.ordertype_id' => $ordertype_ids, 'Order.date >=' => $search_date), 'recursive' => -1));
	//	debug($orders);
		$expelled_ids = array();
		
		foreach ($orders as $order):
			array_push($expelled_ids, $order['Order']['student_id']);
		endforeach;
		//debug($expelled_ids);
		
		$this->loadModel('Student');
		$students = $this->Student->find('all', array('conditions' => array('Student.id' => $expelled_ids)));
		//debug($students);
		
		$this->set('students', $students);
		$this->set('ordertype_ids',$ordertype_ids);
		
		$this->render('/', 'blank', 'lastyearexpelled');
	}
	function listcommstudentsdata() {
		//Configure::write('debug', 0);
		
		$this->loadModel('Student');	
		$this->loadModel('Contract');
		
		
		$this->loadModel('Facultet');
		$this->loadModel('Profession');
		$this->loadModel('Course');
		$this->loadModel('Studentgroup');
		
		$facultets = $this->Facultet->find('list');
		$this->set('facultets', $facultets);
		$professions = $this->Profession->find('all', array('recursive' => -1));
		$this->set('professions', $professions);
		$courses = $this->Course->find('all', array('recursive' => -1));
		$this->set('courses', $courses);
		$studentgroups = $this->Studentgroup->find('all', array('recursive' => -1));
		$this->set('studentgroups', $studentgroups);
		
		$students = $this->Student->find('all', array('conditions' => array('Student.studentstate_id' => 1, 'Student.learningtype_id' => 2),'fields' => array('Student.id'),  'order' => 'Student.learningform_id'));
		$studinfo_ids = array();
		foreach ($students as $student):
			array_push($studinfo_ids, $student['Studentinfo'][0]['id']);
		endforeach;
		
		$contracts = $this->Contract->find('all', array('conditions' => array('Contract.studentinfo_id' => $studinfo_ids), 'recursive' => 2));
		//debug($professions);
		$this->set('students', $contracts);
		
		$this->render('/', 'blank', 'listcommstudentsdata');
	}
}
?>